﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;

namespace auxiliary_proj
{
    public partial class FormNewItem : Form
    {
        //bools for textbox validity
        bool tbVendorCode_valid = false;
        bool tbDescription_valid = false;
        public FormNewItem()
        {
            InitializeComponent();

            //register tooltips
            ToolTip tt = new ToolTip();
            tt.SetToolTip(tbDescription, "Valid Inputs: 0-9, a-z, A-Z [space], -, /\nMin: 2, Max: 100");
            tt.SetToolTip(tbVendorCode, "Valid Inputs: 0-9, a-z, A-Z\nMin:4, Max: 10");

            //event handlers
            this.tbVendorCode.TextChanged += new System.EventHandler(this.tbVendorCode_TextChanged);
            this.tbDescription.TextChanged += new System.EventHandler(this.tbDescription_TextChanged);


            /////////////////////////////////////////////////////////
            ////////////// UPDATE CATID_DESC HASHTABLE //////////////
            /////////////////////////////////////////////////////////
            //run query to get category names and id's
            Query.populateHashtable("CATID_DESC" ,"");
            Query.populateHashtable("VENDORCODE_ITEMID", "");

            //create array of hashtable key/value pairs' count
            string[] catNames = new string[Query.CATID_DESC.Count];

            //turn the ICollection of values into an array
            Query.CATID_DESC.Values.CopyTo(catNames, 0);

            //add array of values to the combo-box
            cbCategory.Items.Clear();
            cbCategory.Items.AddRange(catNames);

            //select index 0 as default
            cbCategory.SelectedIndex = 0;
            /////////////////////////////////////////////////////////
            populateVendor_ID();
            cbVendor.SelectedIndex = 0;
            
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            //only accept the button if both text fields are valid
            if (tbVendorCode_valid && tbDescription_valid)
            {
                //check to see of the vendor code already exists
                string vendorCode = tbVendorCode.Text;
                string queryExist = "SELECT vendorCode FROM ITEM WHERE vendorCode = '" + vendorCode + "'";

                MySqlConnection conn = new MySqlConnection(Program.getConnection());
                try
                {
                    conn.Open();
                    //command q conn
                    MySqlCommand com = new MySqlCommand(queryExist, conn);

                    //datareader
                    MySqlDataReader res = com.ExecuteReader();

                    //if there is a result, vendor code already exists, give error
                    if (res.HasRows)
                        MessageBox.Show("Vendor Code already exists!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    else
                    {
                        //get key based on value
                        int key = (int)Query.getKeyByValue(Query.CATID_DESC, cbCategory.SelectedItem.ToString());
                        //-1 is returned if not found, set to 1100012 (misc), otherwise keep id
                        int cat_id = (key == -1) ? 1100012 : key;
                        //inputs are valid, and vendor code doesn't exists, create new item
                        string q = "INSERT INTO ITEM (vendorCode, description, cat_id, vendor_id) values('" + tbVendorCode.Text + "','" + tbDescription.Text + "'," + cat_id + ",'" + cbVendor.Text + "')";
                        Query.nonQuery(q);

                        Query.populateHashtable("VENDORCODE_ITEMID", "");
                        string item_id = Query.VENDORCODE_ITEMID[tbVendorCode.Text].ToString();

                        string q2 = "INSERT INTO item_quantity(item_id, quantity, price) values ('" + item_id + "', '0','')";
                        Query.nonQuery(q2);
                       
                        if(cbVendor.Text == (Singleton.getUCPurchaseOrder().cbVendor_name.Text))
                        {
                            string vendor_item = tbDescription.Text + " - " + tbVendorCode.Text;
                            Singleton.getUCPurchaseOrder().lbItems.Items.Add(vendor_item);
                        } 
                    }
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show("FormNewItem btnCreate_Click: " + ex.Message);
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();                   
                }             
            }
            else
                MessageBox.Show("You have invalid inputs!","", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void populateVendor_ID()
        {
            cbVendor.Items.Clear();
            DataTable res = Query.select("SELECT vendor_id FROM vendor");

            foreach (DataRow row in res.Rows)
            {
                cbVendor.Items.Add(row["vendor_id"].ToString());
            }
        }

        private void tbVendorCode_TextChanged(object sender, EventArgs e)
        {
            //test pattern on input
            tbVendorCode_valid = Parser.isMatch(sender, "^[a-zA-Z0-9]{4,10}$");
        }

        private void tbDescription_TextChanged(object sender, EventArgs e)
        {
            //test pattern on input
            tbDescription_valid = Parser.isMatch(sender, "^[a-zA-Z0-9 /-]{2,100}$"); 
        }
    }
}
